﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.hhxApplication.Commands.User
{
    public class LoginHandler : IRequestHandler<LoginCommand, Result>
    {
        private readonly IBaseRepository<Users> usersRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="usersRepository"></param>
        public LoginHandler(IBaseRepository<Users> usersRepository)
        {
            this.usersRepository = usersRepository;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var list = await (await usersRepository.GetAll()).Where(d => d.UserName == request.UserName && d.UserPwd == request.UserPwd).FirstOrDefaultAsync();
                if (list != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = list;
                    result.Msg = "用户登录成功";
                }
            }
            catch (Exception)
            {
                result.Msg = "用户登录异常";
            }
            return result;
        }
    }
}
